package com.ifnk.portaljava.hlyt.test;

import com.ifnk.portaljava.dapWeb.common.Util;
import com.ifnk.portaljava.dapWeb.dapweb.CDRBean;
import com.ifnk.portaljava.dapWeb.dapweb.Command;
import com.ifnk.portaljava.dapWeb.dapweb.SignallingPacket;
import com.ifnk.portaljava.dapWeb.hlyt.servlet.CallTraceServlet;
import com.ifnk.portaljava.dapWeb.pacp.Pacp_file_header;
import com.ifnk.portaljava.dapWeb.socket.Client;
import com.ifnk.portaljava.hlyt.service.IDeviceLookupService;
import com.ifnk.portaljava.hlyt.springutil.ServiceLocator;
import flex.messaging.FlexContext;
import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class Tshark extends Thread {

    private static Log loger = LogFactory.getLog(Tshark.class);

    // private CDRBean cdrBean;
    private int index = 0;
    private int sleepTimes = 0;

    // private ArrayList<Integer> list = new ArrayList<Integer>();
    private String clientId;
    private String sessionId;
    private String key;
    // private boolean endFlag = false;
    private CdrPktInfo cdrPktInfo;
    private SignallingPacket signallingPacket = new SignallingPacket();

    public static String tshark = "/opt/wireshark-1.12.2/bin/tshark";
    public static String tshark2 = "/opt/wireshark-1.12.2/bin/tshark";
    public static String pcapfilepath = "/home/dap/portal/PCAPDATA";
    public static String pcapNativeFile = "/home/dap/portal/RawData";
    public static String psml = " -T psml ";
    public static String pdml = " -T pdml ";
    public static String pml_encoding = "UTF-8";

    private int xmlNullTime = 0;

    static {
        loadSetting();
    }

    private static void loadSetting() {

        try {
            loger.debug("init tshark class --start -- ");

            loger.debug("init tshark class --1 -- ");
            Locale locale = Locale.ENGLISH;

            loger.debug("init tshark class --2 --  locale");
            ResourceBundle localResource = ResourceBundle.getBundle("Socket",
                    locale);

            loger.debug("init tshark class --3 -- tshark cmd");
            tshark = localResource.getString("tshark");

            loger.debug("init tshark class --4 -- tshark2 cmd");
            tshark2 = localResource.getString("tshark2");

            loger.debug("init tshark class --5 -- pcapfilepath");
            pcapfilepath = localResource.getString("pacpfilepath");

            loger.debug("init tshark class --6 -- psml");
            psml = localResource.getString("psml");

            loger.debug("init tshark class --7 -- pdml");
            pdml = localResource.getString("pdml");

            loger.debug("init tshark class --8 -- loading pcapNativeFile ");
            pcapNativeFile = localResource.getString("pcapNativeFile");

            /*
             * loger.debug("init tshark class --9 -- loading encoding setting ");
             * pml_encoding = localResource.getString("pml_encoding");
             * loger.debug("inited tshark class --9 -- " + pml_encoding);
             */

        } catch (MissingResourceException e) {
            // NullPointerException - if key is null
            // MissingResourceException - if no object for the given key can be
            // found
            // ClassCastException - if the object found for the given key is not
            // a string
            // TODO: handle exception

        }

    }

    public Tshark(CdrPktInfo cdrPktInfo) {
        this.cdrPktInfo = cdrPktInfo;
        clientId = cdrPktInfo.getClientId();
        sessionId = cdrPktInfo.getSessionId();
        key = cdrPktInfo.getCdrKey();
        Tshark.loadSetting();
    }

    @Override
    public void run() {
        try {
            sleep(600);
            // loger.debug("sleep 600 over");
        } catch (InterruptedException e1) {
            loger.debug("tshark interrupted! exit");
            return;
        }

//        while (true) {
//            if (!cdrPktInfo.isEndFlag()) {
//
//                if (cdrPktInfo.getPktIndex() > cdrPktInfo.getSummaryIndex()) {
//                    sleepTimes = 0;
//                    Document pktXml = getSummaryDecodingXML(0);
//                    // cdrPktInfo.setSummaryDecode(true);
//                    if (pktXml == null) {
//                        loger.debug("pktXml is null!");
//                        xmlNullTime++;
//                        if (xmlNullTime > 3600) {
//                            return;
//                        }
//                        continue;
//                    }
//                    List nodes = pktXml.selectNodes("//packet");
//                    cdrPktInfo.setSummaryIndex(nodes.size());
//                    pktXml.getRootElement().addAttribute("endFlag", "0");
//                    pktXml.getRootElement().addAttribute("key", key);
//                    // TODO:  这里不会走到 end 的 pktXml
//                    System.out.println("pktXmlResult = notEnd  " + pktXml.asXML());
////                    sendPacketToFlex("message" + clientId, clientId, pktXml
////                            .asXML());
//                } else {
//                    try {
//                        if (sleepTimes >= (1200 * 5)) {
//                            loger.debug("tshark thread quit because time out!");
//                            return;
//                        }
//                        sleepTimes++;
//                        sleep(100);
//                    } catch (InterruptedException e) {
//                        loger.debug("tshark interrupted! exit");
//                        return;
//                    }
//                }
//            } else { // end flag
//                if (cdrPktInfo.getPktIndex() > cdrPktInfo.getSummaryIndex()) {
//                    Document pktXml = getSummaryDecodingXML(0);
//                    if (pktXml == null) {
//                        loger.debug("pktXml is null!");
//                        // sleep();
//                        // continue;
//                        return;
//                    }
//                    // cdrPktInfo.setSummaryDecode(true);
//                    cdrPktInfo.setSummaryIndex(pktXml.selectNodes("//packet")
//                            .size());
//                    pktXml.getRootElement().addAttribute("endFlag", "1");
//                    pktXml.getRootElement().addAttribute("key", key);
//                    loger.debug("end : " + pktXml.asXML());
//                    System.out.println("pktXml = endFlag " + pktXml.asXML());
////                    sendPacketToFlex("message" + clientId, clientId, pktXml
////                            .asXML());
//                }
//                return;
//            }
//        }
    }

    // 读取summary list
    public Document getSummaryDecodingXML(int num) {
        Document pktXml = null;
        // byte[] packet = getPcap(pcapNativeFile + File.separator + sessionId
        // + File.separator + key, num);
        //String filename = pcapfilepath + "summary" + File.separator + sessionId + File.separator + key + File.separator + key + ".pcap";

        Path filename = Paths.get(pcapfilepath, "summary", sessionId, key, key + ".pcap");

        System.out.println("filename = " + filename);


        String tsharkArgu = cdrPktInfo.getTsharkArgu() == null ? ""
                : cdrPktInfo.getTsharkArgu();


        String tsharkChinese = cdrPktInfo.getTsharkChineseArgu();
        String tsharkcmd = tshark + " -r " + filename + " " + tsharkArgu + " "
                + tsharkChinese + " " + psml;


        File file = new File(filename.toString());
        int i = 0;
        while (file.length() == 0) {
            if (i > 20) {
                return pktXml;
            }
            try {
                i++;
                // loger.debug("file.length = " + file.length() + " : " + i);
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        InputStream in = RunTsharkIFNK(tsharkcmd);

        try {
            pktXml = readXMLFile(in);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pktXml;
    }

    public static Document getDetailedDecodingXML(String cdrKey, int sequenceNo) {
        Document pktXml = null;
        Client client = (Client) FlexContext.getHttpRequest().getSession()
                .getAttribute("client");
        String sessionId = client.getCp().getRequestDateFromProxyId();
        String filename = pcapfilepath + "summary" + File.separator + sessionId
                + File.separator + cdrKey + File.separator + cdrKey + ".pcap";

        String tsharkArgu = client.getCp().cdrPktInfoMap.get(cdrKey)
                .getTsharkArgu();
        String tsharkChinese = client.getCp().cdrPktInfoMap.get(cdrKey)
                .getTsharkChineseArgu();
        String tsharkcmd = tshark + " -r " + filename + " " + tsharkArgu + " "
                + tsharkChinese + " " + pdml;

        // InputStream in = RunTshark(tsharkcmd);
        InputStream in = RunTshark(tsharkcmd);
        try {
            pktXml = parse(in);
            // OutputStreamWriter osw = new OutputStreamWriter(new
            // FileOutputStream(new File("C:\\root\\d\\test.txt")));
            // osw.write(pktXml.asXML());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return pktXml;
    }

    public static Document getDetailedDecodingXMLII(String cdrKey,
                                                    int sequenceNo, String clientId) {
        Document pktXml = null;
        /*
         * Client client = (Client) FlexContext.getHttpRequest().getSession()
         * .getAttribute("client");
         */
        Client client = CallTraceServlet.getClient(clientId);
        if (client == null) {
            loger.info("client@" + clientId + " is NULL!!!");
        }
        String sessionId = client.getCp().getRequestDateFromProxyId();
        // TODO: find out cdrKey using ALL or real cdrkey
        loger.info("tsharkcmd cdrkey:" + cdrKey);

        String filename = pcapfilepath + "summary" + File.separator + sessionId
                + File.separator + cdrKey + File.separator + cdrKey + ".pcap";

        String tsharkArgu = client.getCp().cdrPktInfoMap.get(cdrKey)
                .getTsharkArgu();
        String tsharkChinese = client.getCp().cdrPktInfoMap.get(cdrKey)
                .getTsharkChineseArgu();
        String tsharkcmd = tshark + " -r " + filename + " " + pdml + " "
                + tsharkArgu + " " + tsharkChinese;

        InputStream in = RunTshark(tsharkcmd);
        try {
            pktXml = parse(in);
            // OutputStreamWriter osw = new OutputStreamWriter(new
            // FileOutputStream(new File("C:\\root\\d\\test.txt")));
            // osw.write(pktXml.asXML());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return pktXml;
    }

    public void savePacketToNativeFile(String filename, byte[] packet,
                                       boolean append) throws IOException {
        File file = new File(filename);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        DataOutputStream output = new DataOutputStream(new FileOutputStream(
                file, append));
        output.write(packet);
        output.flush();
        output.close();
    }

    public byte[] getPcap(String fileName, int num) {
        FileInputStream in = null;
        File file = new File(fileName);
        int pos = 0;
        byte[] dataPacket = new byte[1024 * 1000];
        byte[] filePacket = null;
        if (file.exists()) {
            // pcap文件头
            Pacp_file_header pcapfile = new Pacp_file_header();
            byte[] fileHeader = pcapfile.fileHeader();
            System.arraycopy(fileHeader, 0, dataPacket, 0, fileHeader.length);
            pos = fileHeader.length;
            File[] files = file.listFiles();
            Util.fileSort(files);
            try {
                int i = num;
                for (; i < files.length; i++) {
                    // loger.debug(files[i].getName());
                    in = new FileInputStream(files[i]);
                    byte[] data = new byte[(int) files[i].length()];
                    in.read(data);
                    byte[] packet = signallingPacket
                            .TransformToDataPacket(data);
                    System.arraycopy(packet, 0, dataPacket, pos, packet.length);
                    pos = pos + packet.length;
                    data = null;
                    packet = null;
                }
                index = i;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            filePacket = new byte[pos];
            System.arraycopy(dataPacket, 0, filePacket, 0, pos);

        }
        return filePacket;
    }

    public Document readXMLFile(InputStream in) throws DocumentException,
            IOException {
        SAXReader sax = new SAXReader();

        sax.setEncoding(pml_encoding);
        Document document = sax.read(in);
        Element root = document.getRootElement();
        // 取得structure节点
        Element structure = root.element("structure");
        // 取得structure节点的所有子节点
        List nodes = structure.elements();
        Iterator its = nodes.iterator();
        List header = new ArrayList();
        while (its.hasNext()) {
            Element section = (Element) its.next();
            String value = section.getText();
            value = value.replace(" ", "_");
            if ("No.".equals(value)) {
                value = "No";
            }
            header.add(value);
        }

        // 取得所有的packet节点的集合
        List packets = root.elements("packet");
        Iterator ps = packets.iterator();
        List values = new ArrayList();
        while (ps.hasNext()) {
            // 每一个packet节点
            Element packet = (Element) ps.next();
            // 给packet添加SequenceNo属性
            // 取得packet节点下的所有的section节点的集合
            List sections = packet.elements();
            Iterator it = sections.iterator();
            List value = new ArrayList();
            while (it.hasNext()) {
                // 每一个section节点
                Element element = (Element) it.next();
                // 取得section节点的值
                String text = element.getText();
                value.add(text);
            }
            values.add(value);
        }
        return XMLDocumenttoString(header, values);
    }

    public Document XMLDocumenttoString(List header, List values) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Iterator it = values.iterator();
        while (it.hasNext()) {
            Element packet = root.addElement("packet");
            List list = (List) it.next();
            Iterator valueIt = list.iterator();
            Iterator headIt = header.iterator();
            while (valueIt.hasNext() && headIt.hasNext()) {
                String field = (String) headIt.next();
                String fakevalue = (String) valueIt.next();
                IDeviceLookupService dlup = (IDeviceLookupService) ServiceLocator
                        .getBean("IDeviceLookupService");
                String realvalue = null;
                try {
                    // todo 这里是把 设备ip 替换 成  设备名字 ，后面 在做
                    // realvalue = dlup.findDeviceName(fakevalue);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (realvalue != null) {
                    fakevalue = realvalue;
                }
                /*
                 * packet.addElement((String) field).setText( (String)
                 * valueIt.next());
                 */
                packet.addElement((String) field).setText(fakevalue);
            }
        }
        return document;
    }

    public void sendPacketToFlex(String subTopic, String clientId, Object obj) {
        MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
        AsyncMessage msg = new AsyncMessage();
        msg.setDestination("callTraceChannel");
        msg.setHeader("DSSubtopic", subTopic);
        msg.setClientId(clientId);
        loger.debug("subTopic: " + subTopic);
        msg.setMessageId(UUIDUtils.createUUID());
        msg.setTimestamp(System.currentTimeMillis());
        msg.setBody(obj);
        messageBroker.routeMessageToService(msg, null);
    }

    public static InputStream RunTshark(String tsharkcmd) {
        InputStream in = null;
        try {
            System.out.println("准备解析 pcap文件");

            System.out.println("tsharkcmd = " + tsharkcmd);

            // ProcessBuilder pb = new
            // ProcessBuilder(cmds).redirectErrorStream(false);
            // Process process = pb.start();

            List<String> a = new ArrayList<String>();
            for (String s : tsharkcmd.split(" ")) {
                a.add(s);
            }
            for (int i = 0; i < a.size(); i++) {
                if (a.get(i).contains("+"))
                    a.set(i, a.get(i).replace('+', ' '));
            }
            String[] aaa = new String[a.size()];
            aaa = a.toArray(aaa);

            Process process = Runtime.getRuntime().exec(aaa);
            in = new BufferedInputStream(process.getInputStream());

            final BufferedInputStream err = new BufferedInputStream(process
                    .getErrorStream());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {

                        String line = null;
                        InputStreamReader isr = new InputStreamReader(err);
                        BufferedReader br = new BufferedReader(isr);
                        while ((line = br.readLine()) != null) {
                            System.out.println("tsharkcmd[error]: " + line);

                        }
                        // br.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                }
            }).start();

            /*
             * final BufferedInputStream outy = new BufferedInputStream(process
             * .getInputStream()); new Thread(new Runnable() {
             *
             * @Override public void run() { try {
             *
             * String line = null; InputStreamReader isr = new
             * InputStreamReader(outy); BufferedReader br = new
             * BufferedReader(isr); while ((line = br.readLine()) != null) {
             * loger.debug("tsharkcmd[outy]: " + line); } } catch (IOException
             * ioe) { ioe.printStackTrace(); } } }).start();
             */

            int i = 0;
            while (true) {
                if (in.available() <= 0) {
                    i++;
                    if (i > 20) {
                        i = 0;
                        break;
                    }
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                } else if (in.available() > 0) {
                    i = 0;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return in;
    }

    //我自己写的 把tshark 执行命令 返回的xml 文件 转换成 流
    public static InputStream RunTsharkIFNK(String tsharkcmd) {
        List<String> a = new ArrayList<String>(Arrays.asList(tsharkcmd.split(" ")));
        for (int i = 0; i < a.size(); i++) {
            if (a.get(i).contains("+"))
                a.set(i, a.get(i).replace('+', ' '));
        }
        String[] aaa = new String[a.size()];
        aaa = a.toArray(aaa);
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(aaa);
        try {
//            System.out.println(String.join(" ", processBuilder.command()));
            Process process = processBuilder.start();
            String res = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
            InputStream inputStream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));
            return inputStream;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Document parse(InputStream inn) throws IOException,
            DocumentException {
        SAXReader sax = new SAXReader();
        InputStreamReader strInStream = new InputStreamReader(inn, pml_encoding);

        // File justfile = new
        // File("c:\\root\\d\\portable\\WiresharkPortable\\App\\Wireshark\\test.xml");
        // FileInputStream justtest = new FileInputStream(justfile);
        // InputStreamReader strInStream = new InputStreamReader(justtest);
        // Document document = sax.read(new BufferedInputStream(new
        // FileInputStream("c:\\root\\d\\portable\\WiresharkPortable\\App\\Wireshark\\test.xml")));

        Document document = sax.read(strInStream);
        // 将proto节点的名字改为field
        List pro = document.selectNodes("//proto");
        Iterator itr = pro.iterator();
        while (itr.hasNext()) {
            Element element = (Element) itr.next();
            element.setName("field");
        }

        // commit out in cleaning coding round
        // String xml = null;

        List list = document.selectNodes("//field");
        Iterator it = list.iterator();
        int i = 1;
        while (it.hasNext()) {
            Element fieldElement = (Element) it.next();
            Attribute attr = fieldElement.attribute("showname");
            // 如果没有showname属性，则获取show属性值并把show属性改为showname
            if (attr == null) {
                attr = fieldElement.attribute("show");
                if (attr != null) {
                    fieldElement.addAttribute("showname", attr.getValue());
                    fieldElement.remove(attr);
                } else { // if show is null then
                    /*
                     */
                    attr = fieldElement.attribute("name");
                    fieldElement.addAttribute("showname", attr.getValue());
                }
            }
            fieldElement.addAttribute("id", "" + i++);
            Attribute hide = fieldElement.attribute("hide");
            if (hide != null && "yes".equals(hide.getValue())) {
                fieldElement.getParent().remove(fieldElement);
            }
        }

        // 删除name=geninfo的节点
        Iterator geninfos = document.getRootElement().selectNodes(
                "//field[@name='geninfo']").iterator();
        Iterator packets = document.selectNodes("//packet").iterator();
        while (packets.hasNext()) {
            if (geninfos.hasNext()) {
                Element node = (Element) geninfos.next();
                ((Element) packets.next()).remove(node);
            }
        }

        // 删除packet节点
        // why delete packet nodes when packet size == 1 ???
        /*
         * if (document.getRootElement().elements().size() == 1) { Element
         * packet = document.getRootElement().element("packet"); List nodes =
         * packet.elements(); document.getRootElement().remove(packet);
         * document.getRootElement().setContent(nodes); }
         */

        List lists = document.selectNodes("//field");
        Iterator its = lists.iterator();
        while (its.hasNext()) {
            Element field = (Element) its.next();
            if (field.attribute("show") == null
                    && field.attribute("showname") == null) {
                List fiel = field.elements();
                if (fiel.size() > 0) {
                    Element first = (Element) fiel.get(0);
                    List second = first.elements();
                    List itor = first.attributes();
                    field.setAttributes(itor);
                    field.remove(first);
                    field.setContent(second);
                }
            }
        }
        return document;
    }

    public static CDRBean readBinaryToString(byte[] data, CDRBean cdrBean) {
        String pktStr = "";
        for (int i = 0; i < data.length; i++) {
            pktStr += Integer.toHexString(data[i] & 0xFF) + "; ";
        }
        // 十六进制的数据
        StringBuilder binary = new StringBuilder();
        StringBuilder text = new StringBuilder();
        byte temp = 0;
        for (int i = 0; i < data.length; i++) {
            temp = data[i];
            // 以十六进制的无符号整数形式返回一个字符串表示形式。
            String str = Integer.toHexString(temp);
            if (str.length() == 8) {// 去掉补位的f
                str = str.substring(6);
            }
            if (str.length() == 1) {
                str = "0" + str;
            }
            binary.append(str.toUpperCase());
            // 转换成ascii码
            String ascii = "";
            if (temp > 34 && temp < 127) {
                char c = (char) temp;
                ascii = c + "";
            } else {
                ascii = ".";
            }
            text.append(ascii);
        }
        // 计算行数
        int line = (text.toString().length() % 16 == 0) ? text.toString()
                .length() / 16 : text.toString().length() / 16 + 1;
        // loger.debug(line);
        StringBuilder lines = new StringBuilder();
        for (int i = 0; i < line; i++) {
            String li = Integer.toHexString(i) + "0";
            if (li.length() == 2) {
                li = "00" + li;
            }
            if (li.length() == 3) {
                li = "0" + li;
            }
            lines.append(li);
        }
        cdrBean.setLine(lines.toString());
        cdrBean.setBinary(binary.toString());
        cdrBean.setText(text.toString());
        // loger.info("readBinaryToString: " + pktStr);
        // loger.info("binary " + cdrBean.getBinary());
        // loger.info("line " + cdrBean.getLine());
        return cdrBean;
    }

    public static void saveTreeFile(String fileName, String value) {
        // loger.debug(value);
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write(value);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static CDRBean getDetailedDecodingCDRBeanII(String cdrKey,
                                                       int sequenceNo, String clientId) {
        CDRBean cdrBean = new CDRBean();
        cdrBean.setIndex(sequenceNo);

        /*
         * Client client = (Client) FlexContext.getHttpRequest().getSession()
         * .getAttribute("client");
         */

        Client client = CallTraceServlet.getClient(clientId);

        String sessionId = null;
        if (client == null) {
            sessionId = clientId;
        } else {
            sessionId = client.getCp().getRequestDateFromProxyId();
        }

        String filename = pcapfilepath + "detailed" + File.separator
                + sessionId + File.separator + cdrKey + File.separator
                + (sequenceNo + 1) + ".tree";
        /*
         * File treeFile = new File(filename); if(treeFile.exists()) {
         * FileInputStream in = null; byte[] packet = null; try { in = new
         * FileInputStream(treeFile); packet = new byte[(int)
         * treeFile.length()]; in.read(packet); } catch (FileNotFoundException
         * e) { e.printStackTrace(); } catch (IOException e) {
         * e.printStackTrace(); } finally { try { in.close(); } catch
         * (IOException e) { e.printStackTrace(); } } cdrBean.setTree(new
         * String(packet));
         *
         * int complementCode = (((packet[4] & 0xf3) << 8 | packet[5]) == 0x04)
         * ? 2 : 0; byte[] data = new byte[packet.length - (20 +
         * complementCode)];
         *
         * System.arraycopy(packet, 20 + complementCode, data, 0, packet.length
         * - (20 + complementCode)); Tshark.readBinaryToString(data, cdrBean);
         * return cdrBean;
         *
         * } else {
         */

        if (true) {
            if (client == null) {
                loger.info("client@" + clientId + " is NULL!!!");

                Tshark3 t3 = CallTraceServlet.getTshark3(clientId);
                if (t3 != null) {
                    // Document doc = getDetailedDecodingXMLII(cdrKey,
                    // sequenceNo, clientId);
                    Document doc = t3.getDetailXml();
                    /*
                     * List<Element> packets =
                     * doc.getRootElement().selectNodes("//packet"); String s =
                     * pcapfilepath + "detailed" + File.separator + sessionId +
                     * File.separator + cdrKey + File.separator; for(int i = 0;
                     * i < packets.size(); i++) {
                     * //loger.debug(packets.get(i).asXML());
                     * Tshark.saveTreeFile(s + (i + 1) + ".tree",
                     * packets.get(i).asXML()); }
                     */
                    cdrBean.setTree(((Element) doc.selectNodes("//packet").get(
                            sequenceNo)).asXML());

                    byte[] packet = null;
                    packet = t3.getPKT(sequenceNo);
                    if (packet != null) {
                        byte[] data = packet;
                        Tshark.readBinaryToString(data, cdrBean);
                    }

                }
                return cdrBean;

            } else {

                Document doc = getDetailedDecodingXMLII(cdrKey, sequenceNo,
                        clientId);
                List<Element> packets = doc.getRootElement().selectNodes(
                        "//packet");
                String s = pcapfilepath + "detailed" + File.separator
                        + sessionId + File.separator + cdrKey + File.separator;
                for (int i = 0; i < packets.size(); i++) {
                    // loger.debug(packets.get(i).asXML());
                    Tshark.saveTreeFile(s + (i + 1) + ".tree", packets.get(i)
                            .asXML());
                }
                cdrBean.setTree(((Element) doc.selectNodes("//packet").get(
                        sequenceNo)).asXML());

                byte[] packet = null;

                Command c = client.getCp().getCh().getCommandByPcapNo(
                        sequenceNo);
                if (c != null)
                    packet = c.getPkt();
                if (packet == null)
                    return null;

                int complementCode = (((packet[4] & 0xf3) << 8 | packet[5]) == 0x04) ? 2
                        : 0;
                byte[] data = new byte[packet.length - (20 + complementCode)];
                System.arraycopy(packet, 20 + complementCode, data, 0,
                        packet.length - (20 + complementCode));
                Tshark.readBinaryToString(data, cdrBean);
                return cdrBean;
            }
        } else
            return null;

        /*
         * String pcapNativeFile = Tshark.pcapNativeFile; File file = new
         * File(pcapNativeFile + sessionId + File.separator + cdrKey +
         * File.separator + new
         * java.text.DecimalFormat("000000").format(sequenceNo + 1) + ".dat");
         * FileInputStream in;
         */

    }

    public static CDRBean getDetailedDecodingCDRBean(String cdrKey,
                                                     int sequenceNo) {
        CDRBean cdrBean = new CDRBean();
        cdrBean.setIndex(sequenceNo);
        Client client = (Client) FlexContext.getHttpRequest().getSession()
                .getAttribute("client");
        String sessionId = client.getCp().getRequestDateFromProxyId();
        String filename = pcapfilepath + "detailed" + File.separator
                + sessionId + File.separator + cdrKey + File.separator
                + (sequenceNo + 1) + ".tree";
        File treeFile = new File(filename);
        if (treeFile.exists()) {
            FileInputStream in = null;
            byte[] packet = null;
            try {
                in = new FileInputStream(treeFile);
                packet = new byte[(int) treeFile.length()];
                in.read(packet);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            cdrBean.setTree(new String(packet));
        } else {
            Document doc = getDetailedDecodingXML(cdrKey, sequenceNo);
            List<Element> packets = doc.getRootElement()
                    .selectNodes("//packet");
            String s = pcapfilepath + "detailed" + File.separator + sessionId
                    + File.separator + cdrKey + File.separator;
            for (int i = 0; i < packets.size(); i++) {
                // loger.debug(packets.get(i).asXML());
                Tshark.saveTreeFile(s + (i + 1) + ".tree", packets.get(i)
                        .asXML());
            }
            cdrBean.setTree(((Element) doc.selectNodes("//packet").get(
                    sequenceNo)).asXML());
        }
        String pcapNativeFile = Tshark.pcapNativeFile;
        File file = new File(pcapNativeFile + sessionId + File.separator
                + cdrKey + File.separator
                + new java.text.DecimalFormat("000000").format(sequenceNo + 1)
                + ".dat");
        FileInputStream in;
        byte[] packet = null;
        try {
            in = new FileInputStream(file);
            packet = new byte[(int) file.length()];
            in.read(packet);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int complementCode = (((packet[4] & 0xf3) << 8 | packet[5]) == 0x04) ? 2
                : 0;
        byte[] data = new byte[packet.length - (20 + complementCode)];
        System.arraycopy(packet, 20 + complementCode, data, 0, packet.length
                - (20 + complementCode));
        Tshark.readBinaryToString(data, cdrBean);
        return cdrBean;
    }

    public static void clearCdrPktFile(Client client, String cdrKey) {
        String sessionId = client.getCp().getRequestDateFromProxyId();
        String fileName = pcapfilepath + File.separator + "detailed"
                + File.separator + sessionId + File.separator + cdrKey;
        File file = new File(fileName);
        @SuppressWarnings("unused")
        boolean flag = false;
        flag = deleteFile(file);
        fileName = pcapfilepath + File.separator + "summary" + File.separator
                + sessionId + File.separator + cdrKey;
        file = new File(fileName);
        flag = deleteFile(file);
    }

    public static void clearSessionFile(Client client) {
        String sessionId = client.getCp().getRequestDateFromProxyId();
        String fileName = pcapfilepath + File.separator + "detailed"
                + File.separator + sessionId;
        @SuppressWarnings("unused")
        boolean flag = false;
        File file = new File(fileName);
        flag = deleteFile(file);
        fileName = pcapfilepath + File.separator + "summary" + File.separator
                + sessionId;
        file = new File(fileName);
        flag = deleteFile(file);
        fileName = pcapNativeFile + File.separator + sessionId;
        file = new File(fileName);
        flag = deleteFile(file);
    }

    public static boolean deleteFile(File file) {
        // File file = new File(fileName);
        boolean flag = true;
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                for (int i = 0; i < children.length; i++) {
                    flag = flag && deleteFile(children[i]);
                }
            }
            flag = flag && file.delete();
        }
        return flag;
    }

    // public CDRBean getCdrBean() {
    // return cdrBean;
    // }
    //
    // public void setCdrBean(CDRBean cdrBean) {
    // this.cdrBean = cdrBean;
    // }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    // public ArrayList<Integer> getList() {
    // return list;
    // }
    //
    // public void setList(ArrayList<Integer> list) {
    // this.list = list;
    // }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    // public boolean isEndFlag() {
    // return endFlag;
    // }
    //
    // public void setEndFlag(boolean endFlag) {
    // this.endFlag = endFlag;
    // }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public CdrPktInfo getCdrPktInfo() {
        return cdrPktInfo;
    }

    public void setCdrPktInfo(CdrPktInfo cdrPktInfo) {
        this.cdrPktInfo = cdrPktInfo;
    }
}
